<?php

class User extends MX_Controller {

	protected $CI;
	
	private $_redirect = '/welcome';
	
	public function __construct()
	{
		parent::__construct();
		
		$this->CI =& get_instance();
		
		$this->load->library(array('form_validation', 'core'));
		
		$this->load->helper('cookie');
		
		$this->load->model('user_model');
	}
	
	public function index()
	{
		redirect('user/login');
	}
	
	public function login($redirect = '')
	{
		if ($redirect == '') {
			$redirect = $this->_redirect;
		} else {
			$redirect = $this->core->decode($redirect);
		}
		
		$data['title'] = 'Login';
		$data['content'] = 'login';
		$data['heading_title'] = 'Login';
		
		if ( !$this->session->userdata('session_loggedin') ) {
			if ($this->input->post('cmd') == 'login') {
				$username = $this->input->post('username');
				$password = $this->input->post('password');
				
				if ($this->user_model->authGranted($username, $password)) {
					$this->session->set_userdata('session_loggedin', TRUE);
					$this->session->set_userdata('session_user', 'session_user');
					
					// remember
					// set cookie
					$cookie = array(
						'name'   => 'user',
						'value'  => $this->CI->core->encode(serialize(array($username, $password, 'session_user'))), // session_user is session name
						'expire' => '604800',
					);
					set_cookie($cookie);
					
					redirect($redirect);
				} else {
					$this->form_validation->set_error('<p>Username or password is invalid.</p>');
				}
			}
			
		} else {
			if ($redirect != '') {
				redirect($redirect);
			}
		}
		
		$this->load->view('template', $data);
	}
	
	public function logout($redirect = '')
	{
		if ($redirect == '') {
			$redirect = '';
		} else {
			$redirect = $redirect;
		}
		
		$this->load->helper('cookie');
		
		// destroy any cookies
		delete_cookie('user');
		
		// destroy session
		$this->session->sess_destroy();
		
		redirect('user/login/' . $redirect);
	}
}